package com.sky.controller.admin;


import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class FileController {
    //注入AliOssUtil工具类对象
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传接口")
    public Result upload(@RequestParam("file") MultipartFile file) {
        //1.获取文件的原始名
        String originalFilename = file.getOriginalFilename();

        //2.拿到文件的后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //3.生成UUID,拼接后缀名生成文件的最终名称
        String objectName = UUID.randomUUID().toString() + suffix;

        //4.调用接口上传文件到阿里云oss云存储
        try {
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.debug("文件上传错误信息"+e.getMessage());
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
